<template>
  <div class="tinymce-container">
    <Editor :id="tinymceId" v-model="value" :init="init" @onClick="onClick" />
    <div v-if="showBtn" class="tinymce_btn">
      <el-button type="secondary" @click="setInnerlink">
        {{ $t('添加内链') }}
      </el-button>
      <el-button :disabled="wordSearchDisabled" @click="wordSearch">
        {{ $t('检测内容是否有违禁词') }}
      </el-button>
      <el-button @click="imgLocal">{{ $t('图片本地化') }}</el-button>
      <el-button @click="descExtraction">{{ $t('提取简介') }}</el-button>
      <el-button @click="removeInline">{{ $t('去除行内样式') }}</el-button>
    </div>
    <BaseDialog
      :title="$t('检测结果')"
      :dialog-show.sync="dialogShow"
      width="70%"
      class="prohibited"
    >
      <ul class="clear keys">
        <li>
          <span />
          {{ $t('禁用词') }}
        </li>
        <li>
          <span />
          {{ $t('敏感词') }}
        </li>
        <!-- <li><span />行业禁用词</li>
        <li><span />行业敏感词</li> -->
      </ul>

      <div
        class="forbidWordResultsDisplay forbidWordResultsDisplay0"
        style="display: block"
      >
        <div class="forbidWordTit clear">
          <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
            <ul class="layui-tab-title">
              <li :class="contentTitleStyle" @click="showContent">
                {{ $t('结果展示') }}
              </li>
              <li :class="explainWordTitleStyle" @click="showExplain">
                {{ $t('禁用词解释') }}
              </li>
              <div class="right">
                <!-- <a id="upload_idx_0" href="javascript:;" class="upload" data-upload_idx="0">结果下载</a> -->
                <a
                  id="copy_idx_0"
                  href="javascript:;"
                  class="copy"
                  @click="onCopy"
                >
                  {{ $t('复制内容') }}
                </a>
                <div
                  v-show="level2"
                  class="select delLevel"
                  @click="delKeys(2)"
                >
                  {{ $t('删除禁用词') }}
                </div>
                <div
                  v-show="level1"
                  class="select delLevel1"
                  @click="delKeys(1)"
                >
                  {{ $t('删除敏感词') }}
                </div>
              </div>
            </ul>
            <div class="layui-tab-content">
              <div
                v-if="contentTitleStyle == 'layui-this'"
                class="layui-tab-item layui-show"
              >
                <div class="resultsContent" v-html="wordSearchRes.return_str" />
              </div>
              <div v-else class="explainWordContent">
                <ul>
                  <li
                    v-for="item in wordSearchRes.word_list"
                    :key="item.title"
                    class="newwords_title_li"
                  >
                    <div
                      id="title_0"
                      class="tit clear"
                      data-index="0"
                      data-idx="0"
                    >
                      <div class="left newwords_title" style="width: 25%">
                        {{ item.title }}
                      </div>
                      <div class="left" style="width: 50%">
                        {{ $t('词库释义') }}:{{ item.paraphrase }}
                      </div>
                      <div class="left" style="width: 25%">
                        <span>{{ item.type }}</span>
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div style="margin-top: 15px; color: red">
              {{ $t('以上查询结果仅供参考') }}
            </div>
          </div>
          <!--展示结果e-->
        </div>
      </div>
    </BaseDialog>
  </div>
</template>

<script>
import tinymce from 'tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default/icons.min.js'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/media'
import 'tinymce/plugins/lists'
import uploadApi from '@/api/upload'
import columnApi from '@/api/column'
// 下面的插件是自带的,不需要引入
// import 'tinymce/plugins/contextmenu'
// import 'tinymce/plugins/colorpicker'
// import 'tinymce/plugins/textcolor'
export default {
  components: {
    Editor
  },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
      // 给每个tinymce设置不同的id
    },
    tinymceHtml: {
      type: String,
      default: ''
    },
    tinymceHeight: {
      type: Number,
      default: 500
    },
    showBtn: {
      type: Boolean,
      default: true
    },
    articleId: {
      default: ''
    },
    prop: {
      default: ''
    }
  },
  data() {
    return {
      wordSearchDisabled: false,
      explainWordTitleStyle: '',
      contentTitleStyle: 'layui-this',
      wordSearchRes: {
        return_str: '',
        word_list: []
      },
      codeValue: '',
      level1: false,
      level2: false,
      website_id: this.$store.getters.siteId,
      dialogShow: false,
      tinymceId: this.id,
      value: this.tinymceHtml, // 父组件通过ref拿到该组件的值
      init: {
        convert_urls: false,
        selector: '#${this.tinymceId}',
        language_url: 'tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: 'tinymce/skins/ui/oxide', // 编辑器需要一个skin才能正常工作，所以要设置一个skin_url指向之前复制出来的skin文件
        height: this.tinymceHeight,
        plugins: [
          'image',
          'link',
          'code',
          'table',
          'lists',
          'wordcount',
          'media'
        ], // 引入插件
        toolbar:
          'fontselect fontsizeselect link lineheight forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | image media quicklink h2 h3 blockquote table numlist bullist preview fullscreen', // 工具栏
        browser_spellcheck: true, // 拼写检查
        branding: false, // 去水印
        elementpath: true, // 禁用编辑器底部的状态栏
        statusbar: true, // 隐藏编辑器底部的状态栏
        paste_data_images: true, // 允许粘贴图像
        menubar: true, // 隐藏最上方menu
        paste_data_images: true, // 设置为“true”将允许粘贴图像，而将其设置为“false”将不允许粘贴图像。
        file_picker_types: 'media',
        images_upload_credentials: true,
        // init_instance_callback: function(editor) {
        //   editor.on('NodeChange Change KeyUp SetContent', () => {
        //     this.hasChange = true
        //     this.$emit('input', editor.getContent())
        //   })
        // },
        fontsize_formats: '14px 16px 18px 20px 24px 26px 28px 30px 32px 36px', // 字体大小
        font_formats:
          '微软雅黑=Microsoft YaHei,Helvetica Neue;PingFang SC;sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun;serifsans-serif;Terminal=terminal;monaco;Times New Roman=times new roman;times', // 字体
        /**
         * 下面方法是为tinymce添加自定义插入图片按钮
         * 借助iview的Upload组件,将图片先上传到存储云上，再将图片的存储地址放入编辑器内容
         */
        // 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
        images_upload_handler: function (blobInfo, success, failure) {
          const formdata = new FormData()
          formdata.append('file', blobInfo.blob())
          // this.handleImgUpload(blobInfo, success, failure)
          uploadApi
            .upload(formdata)
            .then(res => {
              success(res.data.url)
            })
            .catch(res => {
              failure('error')
            })
        },
        // 自定义文件选择器的回调内容 此方法只有在点击上方图片按钮才会触发
        file_picker_callback: function (callback, value, meta) {
          // 主要判断 media
          if (meta.filetype === 'media') {
            // 动态创建上传input，并进行模拟点击上传操作，达到本地上传视频效果。
            const input = document.createElement('input') // 创建一个隐藏的input
            input.setAttribute('type', 'file')
            input.setAttribute('accept', '.mp4,.avi,.3gp,.rmvb,.mov,.mkv')
            const that = this
            input.onchange = function () {
              const file = this.files[0]
              const fd = new FormData()
              fd.append('file', file)
              uploadApi.upload(fd).then(res => {
                // callback 回调的作用是将所选择的视频的url显示在输入框中
                callback(res.data.url)
              })
            }
            // 触发点击
            input.click()
          }
        }
      }
    }
  },
  computed: {},
  watch: {
    showBtn(newV, oldV) {
      this.showBtn = newV
    },
    tinymceHtml(newV, oldV) {
      this.value = newV
    },
    value: {
      handler(val) {
        this.codeValue = this.transformValue(val)
        this.$emit('update', val)
      },
      immediate: true
    },
    articleId(newv, oldV) {
      this.articleId = newV
    },
    prop(val, value) {}
  },
  created() {
    console.log(this.prop)
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    transformValue(val) {
      let data = val
      const strs = ['"', "'", '<', '>']
      const code = ['&quot;', '&quot;', '&lt;', '&gt;']
      if (val) {
        strs.forEach((item, index) => {
          data = data.replaceAll(item, code[index])
        })
      }
      return data
    },
    onCopy() {
      navigator.clipboard.writeText(this.wordSearchRes.return_str).then(() => {
        this.$message.success('复制成功')
      })
    },
    // 删除禁用词
    delKeys(type) {
      let reg = /<span class="type1"(.*?)>(.*?)<\/span>/g
      if (type == 2) {
        reg = /<span class="type2"(.*?)>(.*?)<\/span>/g
      }

      this.wordSearchRes.return_str = this.wordSearchRes.return_str.replace(
        reg,
        ''
      )
    },
    showContent() {
      this.explainWordTitleStyle = ''
      this.contentTitleStyle = 'layui-this'
    },
    showExplain() {
      this.explainWordTitleStyle = 'layui-this'
      this.contentTitleStyle = ''
    },
    getTin(val) {},
    // 图片本地化
    imgLocal() {
      if (!this.value) {
        this.$message.error('内容不能为空！')
      } else {
        columnApi.imgLocal({ content: this.value }).then(res => {
          if (res.code == 0) {
            this.value = res.data
            this.$message.success(res.msg)
          }
        })
      }
    },
    // 违禁词检测
    wordSearch() {
      console.log(!this.value)

      if (!this.value) {
        this.$message.error('内容不能为空！')
        return
      }
      this.wordSearchDisabled = true
      columnApi.wordSearch({ content: this.value }).then(res => {
        if (res.code == 0) {
          this.wordSearchRes = res.data
          for (const ele in res.data.word_list) {
            if (res.data.word_list[ele].level == 2 && !this.level2) {
              this.level2 = true
            }
            if (res.data.word_list[ele].level == 1 && !this.level1) {
              this.level1 = true
            }
          }
          this.dialogShow = true
        }
        this.wordSearchDisabled = false
      })
    },
    // 提取简介
    descExtraction() {
      console.log(!this.value)
      if (!this.value) {
        this.$message.error('内容不能为空！')
      } else {
        columnApi.descExtraction({ content: this.value }).then(res => {
          if (res.code == 0) {
            this.$emit('changeDescription', res.data)
            this.$message.success(res.msg)
          }
        })
      }
    },
    // 去除行内样式
    removeInline() {
      this.value = this.value.replace(/\sstyle="[^"]*"/g, '')
    },
    // 设置为内链
    setInnerlink() {
      const val = {
        website_id: this.$store.getters.siteId,
        content: this.value,
        sub_id: this.articleId
      }
      // return
      if (!this.value) {
        this.$message.error('内容不能为空！')
      } else {
        columnApi.addInnerChat(val).then(res => {
          if (res.code == 0) {
            this.value = res.data
            this.$message.success(res.msg)
          }
        })
      }
    },
    // 用于上传图片的，后端需要提供好上传接口
    handleImgUpload(blobInfo, success, failure) {
      const formdata = new FormData()
      formdata.set('upload_file', blobInfo.blob())
      const new_headers = { headers: this.headers }
      const upload_url = process.env.BASE_API + '/attachment/uploadAndSave'
      axios
        .post(upload_url, formdata, new_headers)
        .then(res => {
          success(res.data.data[0])
        })
        .catch(res => {
          failure('error')
        })
    },
    onClick(e) {
      this.$emit('onClick', e, tinymce)
    }
  }
}
</script>
<style lang="scss" scoped>
.tinymce_btn {
  margin-top: 5px;
}
::v-deep .type4 {
  color: white;
  background: #0073fc;
  padding: 2px;
}

::v-deep .type3 {
  color: white;
  background: #8a2be2;
  padding: 2px;
}

::v-deep .type2 {
  color: white;
  background: #de0d48;
  padding: 2px;
}

::v-deep .type1 {
  color: white;
  background: #ff871d;
  padding: 2px;
}

.prohibited {
  display: block;
}

.clear::after {
  content: '';
  clear: both;
  display: block;
}
.keys {
  padding: 0;
  margin: 0 20px;
  overflow: hidden;
  li {
    list-style: none;
    float: left;
    line-height: 15px;
    font-size: 13px;
    margin-right: 24px;
    color: #555;
    span {
      display: block;
      float: left;
      margin-right: 12px;
      height: 14px;
      width: 14px;
      border-radius: 2px;
    }
  }
}
.keys li:nth-child(1) span {
  background-color: #de0d48;
}
.keys li:nth-child(2) span {
  background-color: #ff871d;
}
.keys li:nth-child(3) span {
  background-color: #0073fc;
}
.keys li:nth-child(4) span {
  background-color: #8a2be2;
}

.forbidWordResultsDisplay {
  padding-top: 22px;
  margin: 0 24px;
}
.forbidWordResultsDisplay .forbidWordTit {
  margin-bottom: 14px;
}
.forbidWordResultsDisplay .forbidWordTit .tit {
  font-size: 18px;
  color: #333333;
  margin-bottom: 20px;
}

.forbidWordResultsDisplay .forbidWordTit .right a {
  display: block;
  float: left;
  line-height: 28px;
  min-width: 86px;
  border: 1px solid #fff;
  text-align: center;
  font-size: 13px;
  margin-left: 10px;
}
.forbidWordResultsDisplay .forbidWordTit .right .upload {
  padding-left: 16px;
  text-align: left;
  border-color: #0773fc;
  color: #0773fc;
  border-radius: 5px;
}
.forbidWordResultsDisplay .forbidWordTit .right .copy {
  padding-left: 16px;
  padding-right: 14px;
  border-color: #0773fc;
  color: #0773fc;
  border-radius: 5px;
}
.forbidWordResultsDisplay .forbidWordTit .right div {
  padding-left: 16px;
  padding-right: 14px;
  float: left;
  cursor: pointer;
  line-height: 28px;
  color: #f00f0f;
  border: 1px solid #f00f0f;
  text-align: center;
  position: relative;
  margin-left: 10px;
  font-size: 1px;
  border-radius: 5px;
}
.forbidWordResultsDisplay .forbidWordTit .right div ul {
  display: none;
  position: absolute;
  top: 29px;
  width: 100%;
  background: #fff;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}
.forbidWordResultsDisplay .forbidWordTit .right div ul li {
  height: 28px;
}
.forbidWordResultsDisplay .forbidWordTit .right div ul li a {
  font-size: 12px;
  color: #888888;
  line-height: 28px;
  display: block;
  height: 100%;
  border: none;
  float: initial;
  margin-left: -1px;
}
.forbidWordResultsDisplay .forbidWordTit .right div ul li:hover a {
  color: #ec6767;
}
.forbidWordResultsDisplay .resultsContent {
  color: #555555;
  text-align: left;
  font-size: 13px;
  line-height: 22px;
  padding: 24px;
  border: 1px solid rgba(0, 128, 255, 0.1);
  word-wrap: break-word;
}

.forbidWordResultsDisplay .resultsContent ul {
  display: block;
  overflow: hidden;
}
.forbidWordResultsDisplay .resultsContent ul li {
  list-style: none;
}
.forbidWordResultsDisplay .resultsContent .level1 {
  color: #c6cace;
}
.forbidWordResultsDisplay .resultsContent .level2 {
  color: #ffc833;
}
.forbidWordResultsDisplay .resultsContent .level3 {
  color: #ff871d;
}
.forbidWordResultsDisplay .resultsContent .level4 {
  color: #ff1da2;
}
.forbidWordResultsDisplay .resultsContent .level5 {
  color: #ff1d5d;
}
.forbidWordResultsDisplay .explainWord {
  padding-top: 22px;
}
.forbidWordResultsDisplay .explainWord .tit span {
  color: #0080ff;
}
.forbidWordResultsDisplay .explainWordContent {
  display: block;
}
.forbidWordResultsDisplay .explainWordContent ul li {
  list-style: none;
}
.forbidWordResultsDisplay .explainWordContent ul li .tit {
  cursor: pointer;
}
.forbidWordResultsDisplay .explainWordContent ul li .tit div {
  font-size: 13px;
  color: #555;
}
.forbidWordResultsDisplay .explainWordContent ul li .tit div:last-child {
  text-align: right;
}
.forbidWordResultsDisplay .explainWordContent ul li .tit .rotate {
  transform: rotate(180deg);
  text-align: left !important;
}
.forbidWordResultsDisplay .explainWordContent ul .on {
  height: auto;
  padding: 30px 40px;
  transition: all 0.3s;
}
.forbidWordResultsDisplay .explainWordDetails {
  padding: 0px 40px;
  background: #f8f9fa;
  color: #777;
  font-size: 13px;
  line-height: 23px;
  overflow: hidden;
  transition: all 0.3s;
  height: 0;
}

.layui-tab-title li {
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
  transition: all 0.2s;
  -webkit-transition: all 0.2s;
  position: relative;
  line-height: 40px;
  min-width: 65px;
  padding: 0 15px;
  text-align: center;
  cursor: pointer;
}

.layui-tab-brief > .layui-tab-title .layui-this {
  color: #355bff;
}

.layui-tab-title .layui-this:after {
  position: absolute;
  left: 0;
  top: 0;
  content: '';
  width: 100%;
  height: 41px;
  border: none;
  border-radius: 0;
  border-bottom: 2px solid #355bff;
  box-sizing: border-box;
  pointer-events: none;
}
.layui-tab-title {
  position: relative;
  left: 0;
  height: 40px;
  white-space: nowrap;
  font-size: 0;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-color: #eee;
  transition: all 0.2s;
  -webkit-transition: all 0.2s;
}
.layui-tab {
  margin: 10px 0;
  text-align: left !important;
}
.layui-tab-content {
  padding: 15px 0;
  max-height: 50vh;
  overflow-y: auto;
}
.right {
  float: right;
}
.left {
  float: left;
}
.forbidWordResultsDisplay .forbidWordTit .right div.delLevel1 {
  border-color: #ff871d;
  color: #ff871d;
}
</style>
